package threads;

/**
 * @author apple
 * @Classname ThreadVolatileTest
 * @Description 多线程之间的通信方式
 * @Date 2020/4/20 17:20
 */
public class ThreadVolatileTest {
    public static void main(String[] args) {
        notifyWithVolatile();
    }

    /**
     * 定义一个共享内存标识，默认为false
     **/
    private static volatile boolean flag = false;
    private static volatile int count = 0;

    private static void notifyWithVolatile() {
        Thread threadA = new Thread("Thread-A") {
            @Override
            public void run() {
                for (int i = 1; i <= 100; i++) {
                    System.out.println(Thread.currentThread().getName() + "===" + i);
                    if (i % 5 == 0) {
                        count = i;
                        flag = true;
                        try {
                            Thread.sleep(100L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        };

        Thread threadB = new Thread("thread-B") {
            @Override
            public void run() {
                while (true) {
                    while (flag) {
                        System.out.println(Thread.currentThread().getName() + "收到任务通知=" + count);
                        flag = false;
                    }
                }
            }
        };
        threadA.start();
        threadB.start();
    }
}
